import React, { PureComponent } from 'react';
import { Form, Radio, Tree, notification } from 'antd';
import { connect } from 'dva';
import "./form.less"
import { bus } from "../../utils/bus"
const { TreeNode } = Tree;
/***
 * 
 * station=>x;elevation=>y1;ground_elevation=>y2
 */
class CrossSection extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            disabled1: false,
            disabled2: false,
            value: null,
            current: null,
            expandedKeys: [], selectedKeys: [],
            tabs: [],
            showAttr:true,
            tempList: [],
            attrList: []

        }
        this.renderTreeNodes = this.renderTreeNodes.bind(this)
        this.onSelect = this.onSelect.bind(this)
        this.getCrossTree = this.getCrossTree.bind(this)
        this.loopTreeNode = this.loopTreeNode.bind(this)
        this.getTempList = this.getTempList.bind(this).bind(this)
        this.onConfirm = this.onConfirm.bind(this)
        this.radioClick=this.radioClick.bind(this)
    }
    async onSelect(keys, e) {
        const obj = e.node.props;
        this.setState({
            selectedKeys: keys
        })
        if (!obj.parentId) {
            this.getTempList()
            return;
        }
        this.getTempList(obj.id)

    }
    onConfirm(params = {}) {
        return new Promise((resolve, reject) => {
            const { extra } = this.props;
            const nlist = document.querySelectorAll(".content .input");
            const len = nlist.length;
            const { current } = this.state;
            let geoattrs=current.crossSectionTemplateGeoAttrs;
            const len2=geoattrs.length
            let obj = {}
            if (len) {
                for (let i = 0; i < len; i++) {
                    let item = nlist[i];
                    for (let j = 0; j < len2; j++) {
                        let item2 = geoattrs[j];
                        if(item2.keyName==item.dataset.key){
                            item2.defaultValue=item.value*10
                            console.log(item2.keyName)
                        }
                    }
                    if (!item.value) {
                        notification.warn({ message: "请将参数填写完整!" })

                        reject()
                        if (params.onError) {
                            params.onError()
                        }
                        return;
                    } else {
                        obj[item.dataset.key] = item.value
                    }
                }
            }
            obj.temp=current;
            obj.crossSection = current.name;
            obj.value=extra.value;
            obj.cid=current.id;
            
            bus.emit("crossSectionFinish", obj)
            
            if (params.onSuccess) {
                params.onSuccess()
            }
            resolve()
        })
    }
    renderTreeNodes(data) {
        return data.map(item => {
            if (item.children && !item.hidden) {
                return (
                    <TreeNode checkable={item.checkable} title={item.title} key={item.key} dataRef={item}>
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                );
            }
            return !item.hidden ? <TreeNode checkable={item.checkable} title={item.title} key={item.key} {...item} dataRef={item}></TreeNode> : undefined;

        });
    }
    async componentDidMount() {
        const { extra,onLoaded } = this.props;
        if (onLoaded) {
           onLoaded(this);
        }
      
        this.getCrossTree(extra)
        await this.getTempList()
        const { tabs,tempList } = this.state;
        const expandedKeys = tabs.map(item => item.key)
        const obj = extra.temp? extra.temp:(extra.crossSectionTemplate?extra.crossSectionTemplate:tempList.find(item => item.id == extra.value))

        if (obj) {
            this.setState({
                value: obj.id,
                current: obj,
                attrList: [...obj.crossSectionTemplateGeoAttrs, ...obj.crossSectionTemplateAttrs],
                expandedKeys
            });
        }

    }
    loopTreeNode(data, code) {
        function loop(list) {
            if (list && list.length) {
                const len = list.length;
                for (let i = 0; i < len; i++) {
                    let item = list[i]
                    item.title = item.name;
                    item.key = item.id;
                    if (item.level == 2 && item.code != code) {
                        delete list[i]
                    }
                    if (item && item.children && item.children.length) {
                        loop(item.children)
                    } else {
                        continue;
                    }
                }

            }
            return list;
        }
        return loop(data)
    }

    async getCrossTree(extra) {
        let res = this.loopTreeNode(await this.props.crossTree({code:extra.code}), extra.code)

        this.setState({
            tabs: res,
            expandedKeys: res.map(item => String(item.key))
        })

    }
    async radioClick(e,id){
        await this.setState({
            showAttr:false
        })
        const obj = this.state.tempList.find(item => item.id == id)
         this.setState({
            showAttr:true,
            value: id,
            current: obj,
            attrList: [...obj.crossSectionTemplateGeoAttrs, ...obj.crossSectionTemplateAttrs]
        });
    }
    async getTempList(id) {
        const { extra } = this.props;
        let res = await this.props.crossTempList(id ? { crossSectionCategoryId: id,code:extra.code } : { timeX: new Date().getTime(),code:extra.code})
        this.setState({
            tempList: res
        })

    }
    render() {
        const { tabs, selectedKeys, tempList, attrList,showAttr  } = this.state
        return (
            <div style={{ fontSize: "62.5%" }} className="crossSectionBox">
                <div className="left">
                    {
                        tabs && tabs.length ? <Tree style={{ fontSize: "62.5%" }}
                            defaultExpandAll
                            selectedKeys={selectedKeys}
                            treeData={tabs}
                            onSelect={this.onSelect}>
                        </Tree> : undefined
                    }

                </div>
                <div className="middle">
                    <div className="title">
                        选择截面库
                    </div>
                    <div className="content">
                        <Radio.Group  value={this.state.value}>
                            {
                                tempList && tempList.length ? tempList.map(item => {
                                    return <div key={'id'+item.id} className="card">
                                        <div onClick={e=>this.radioClick(e,item.id)}><Radio value={item.id}></Radio></div>
                                        <div>
                                            <div style={{ backgroundImage: `url(${item.uploadFileInfo ? "http://27.17.20.242:8064/fsds/"+item.uploadFileInfo.uploadFilePath : ''})`, backgroundSize: "cover" }}>

                                            </div>
                                            <div>
                                                {item.name}
                                            </div>
                                        </div>
                                    </div>
                                }) : undefined
                            }


                        </Radio.Group>

                    </div>
                </div>
                <div className="right">
                    <div className="title">
                        截面属性信息
                    </div>
                    <div className="content">
                        {showAttr?<Form>
                            <div className="tableBoxS">
                                <table>
                                    <tbody>
                                        {
                                            attrList && attrList.length ? attrList.map((item, index) => {
                                                return <tr key={'prop' + index}>
                                                    <td className="nowrap">{item.name}(cm)</td>
                                                    <td><input data-dv={item.defaultValue/10} defaultValue={item.defaultValue/10} data-key={item.keyName} className="input" type="number" /></td>
                                                </tr>
                                            }) : undefined
                                        }

                                    </tbody>
                                </table>

                            </div>

                        </Form>:undefined}
                    </div>
                </div>
            </div>
        )
    }
}
export default connect(
    ({

    }) => {
        return {};
    },
    dispatch => ({
        crossTree: (values) => dispatch({
            type: 'renforce/crossTree',
            payload: values
        }),
        crossTempList: (values) => dispatch({
            type: 'renforce/crossTempList',
            payload: values
        }),
    })
)(Form.create('CrossSection', {

})(CrossSection));